package dashboard;

import java.util.*;
import java.util.Map.Entry;



public class LeaderboardController {

	
	public LeaderboardController()
	{
	}

	public static Map<String, Double> getTotalDurationOfCourseForAllUsers(String courseName){
		Map<String, Double> result= new TreeMap<String, Double>();
		List<User> users =UserRegistry.getInstance().getAllUsers();
		for(User user: users){
			long courseId= CourseRegistry.getInstance().getCourseId(courseName);
			Double time = Statistics.getCourseDurationUser(user, courseId);
			result.put(user.getUserName(), time);
		}
		return result;
	}

	public static Map<String, Double> getTopTen(Map<String, Double> userDurations){
		Map<String, Double> sortedMap = sortMap(userDurations);
		Map<String, Double> result = new TreeMap<String, Double>();
		Iterator it = sortedMap.entrySet().iterator();
		int i=0;
		while (it.hasNext() && i!=10) {
			Map.Entry pairs = (Map.Entry)it.next();
			double value  = (Double) pairs.getValue();
			String key = (String) pairs.getKey();
			result.put(key, value);
			i++;
		}
		result=sortMap(result);
		return result;
	}


	public static Map<String, Double> sortMap(Map<String, Double> input){
		Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
		while(!input.isEmpty() && input!=null){
			double maxValue=0.000000;
			String maxKey = "";
			Iterator it = input.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry pairs = (Map.Entry)it.next();
				double value  = (Double) pairs.getValue();
				String key = (String) pairs.getKey();
				if(value>=maxValue){
					maxValue=value;
					maxKey=key;
				}
			}
			input.remove(maxKey);
			sortedMap.put(maxKey, maxValue);
		}
		return sortedMap;
	}

	public static Map<String, Double> getTotalSucceededMilestonesPerUser(){
		Map<String, Double> result = new TreeMap<String, Double>();
		List<User> users = UserRegistry.getInstance().getAllUsers();
		for(User user : users){
			double amount = Statistics.amountOfAchievedMilestones(user);
			result.put(user.getUserName(), amount);
		}
		
		return result;
	}

	public static int getPos(Map<String, Double> userDurations, User user){
		Map<String, Double> sortedMap = sortMap(userDurations);
		Iterator it = sortedMap.keySet().iterator();
		int i=1;
		while (it.hasNext()) {
			if(user.getUserName().equals(it.next())){
				return i;
			}
			i++;
		}
		return -1;
	}
	}